import { reqGetShopcartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

export default {

  namespaced: true,

  state: {
    // 服务器响应回来的购物车数据
    shopcartList: []

  },

  actions: {
    // 获取购物车数据
    async getShopcartList({ commit }) {
      const result = await reqGetShopcartList()
      if (result.code === 200) {
        commit('GETSHOPCARTLIST', result.data)
      }
    },
    // 删除购物车商品ById
    async deleteCartById(context, skuId) {
      const result = await reqDeleteCartById(skuId)
      if (result.code === 200) {
        return 'ok'
      } else {
        Promise.reject(new Error('faile'))
      }
    },
    // 删除全部选中的商品
    deleteAllCheckedCart({ dispatch, getters }) {
      const promiseAll = []
      const cartInfoList = getters.shopcartList.cartInfoList
      if (cartInfoList.length > 0) {
        cartInfoList.forEach(item => {
          if (item.isChecked === 1) {
            promiseAll.push(dispatch('deleteCartById', item.skuId))
          }
        })
      }
      return Promise.all(promiseAll)
    },
    // 修改购物车商品的选中状态
    async updateCheckedById(context, { skuId, isChecked }) {
      const result = await reqUpdateCheckedById(skuId, isChecked)
      if (result.code === 200) {
        return 'ok'
      } else {
        Promise.reject(new Error('faile'))
      }
    },
    updateAllCartIsChecked({ dispatch, getters }, isChecked) {
      const promiseAll = []
      getters.shopcartList.cartInfoList.forEach(item => {
        promiseAll.push(dispatch('updateCheckedById', { skuId: item.skuId, isChecked }))
      })
      return Promise.all(promiseAll)
    }

  },

  mutations: {

    GETSHOPCARTLIST(state, shopcartList) {
      state.shopcartList = shopcartList
    }
  },

  getters: {
    shopcartList(state) {
      return state.shopcartList[0] || {}
    }
  }
}
